<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>
<style>
    /*vjs-fluid 自适video 长宽*/
    
    .video {
        /*border: 1px solid gray;*/
        margin-top: .5rem;
        /*width: 2.6rem;*/
        /*height: 3rem;*/
        width: 100%;
    }
    
    .tip {
        color: white;
        font-size: .16rem;
    }
    /* common */
    
    .bgc-f4f4f4 {
        background-color: #363636;
    }
    
    .page {
        overflow-y: auto;
        position: relative;
    }
</style>

<body>
    <div id="app" class="page bgc-f4f4f4">
        <video ref="video" id="video" class="video vjs-fluid" autoplay></video>
        <div v-show="tipShow" class="tip">{{tipMsg}}</div>
    </div>

    <!-- <script src="../script/vue.min.js"></script> -->
    <script src="js/vue.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@zxing/browser@latest"></script>
    <script type="text/javascript">
        // var that = this;
        window.addEventListener('load', async() => {
            // console.log(ZXingBrowser)
            // const codeReader = new ZXingBrowser.BrowserQRCodeReader();

            // const videoInputDevices = await ZXingBrowser.BrowserCodeReader.listVideoInputDevices();
            // // console.log(videoInputDevices)
            // // choose your media device (webcam, frontal camera, back camera, etc.)
            // const selectedDeviceId = videoInputDevices[0].deviceId;

            // console.log(`Started decode from camera with id ${selectedDeviceId}`);

            // const previewElem = document.querySelector('#video > video');

            // // you can use the controls to stop() the scan or switchTorch() if available
            // const controls = await codeReader.decodeFromVideoDevice(selectedDeviceId, previewElem, (result, error, controls) => {
            //     // use the result and error values to choose your actions
            //     // you can also use controls API in this scope like the controls
            //     // returned from the method.
            // });

            // // stops scanning after 20 seconds
            // setTimeout(() => controls.stop(), 20000);
        });
        var app = new Vue({
            el: "#app",
            data() {
                return {
                    loadingShow: false,
                    codeReader: new ZXingBrowser.BrowserQRCodeReader(),
                    textContent: null,
                    vin: null,
                    tipMsg: '正在尝试识别....',
                    tipShow: false
                }
            },
            created() {
                // this.tipShow = true
                this.openScan()
            },
            methods: {
                async openScan() {
                    const that = this;
                    // alert(that.codeReader)
                    // console.log(that.codeReader.decodeFromVideoDevice());
                    ZXingBrowser.BrowserCodeReader.listVideoInputDevices().then((videoInputDevices) => {
                        that.tipShow = true
                        that.tipMsg = '正在调用后置摄像头...'
                        console.log('videoInputDevices', videoInputDevices);
                        // 默认获取第一个摄像头设备id
                        let firstDeviceId = videoInputDevices[0].deviceId;
                        // 获取第一个摄像头设备的名称

                        const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);

                        if (videoInputDevices.length > 1) {
                            // 判断是否后置摄像头
                            if (videoInputDeviceslablestr.indexOf('back') > -1) {
                                firstDeviceId = videoInputDevices[0].deviceId;
                            } else {
                                firstDeviceId = videoInputDevices[1].deviceId;
                                // alert(firstDeviceId)
                            }
                        }
                        that.decodeFromInputVideoFunc(firstDeviceId)
                    }).catch((err) => {
                        that.tipShow = false
                        console.error(err);
                    });
                    // const videoInputDevices = await ZXingBrowser.BrowserCodeReader.listVideoInputDevices();
                    // // console.log(videoInputDevices)
                    // // alert(that.videoInputDevices)
                    // // choose your media device (webcam, frontal camera, back camera, etc.)
                    // const selectedDeviceId = videoInputDevices[0].deviceId;
                    // if (selectedDeviceId) {
                    //     that.tipShow = true
                    //     that.tipMsg = '正在调用后置摄像头...'
                    //     alert(selectedDeviceId)
                    // }
                    // alert(that.videoInputDevices)
                },
                // async openScanTwo() {
                //     const that = this
                //         // codeReader.reset() // 重置
                //         // that.textContent = null // 重置
                //         // that.codeReader = await new BrowserMultiFormatReader()
                //     ZXingBrowser.BrowserCodeReader.listVideoInputDevices().then((videoInputDevices) => {
                //         that.tipShow = true
                //         that.tipMsg = '正在调用后置摄像头...'
                //         console.log('videoInputDevices', videoInputDevices);

                //         // 默认获取第一个摄像头设备id
                //         let firstDeviceId = videoInputDevices[0].deviceId;
                //         // 获取第一个摄像头设备的名称
                //         const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);

                //         if (videoInputDevices.length > 1) {
                //             // 判断是否后置摄像头
                //             if (videoInputDeviceslablestr.indexOf('back') > -1) {
                //                 firstDeviceId = videoInputDevices[0].deviceId;

                //             } else {
                //                 firstDeviceId = videoInputDevices[1].deviceId;
                //             }
                //         }
                //         that.decodeFromInputVideoFunc(firstDeviceId)
                //     }).catch((err) => {
                //         that.tipShow = false
                //         console.error(err);
                //     });
                // },
                decodeFromInputVideoFunc(firstDeviceId) {
                    const that = this
                        // that.codeReader.reset() // 重置
                    that.textContent = null // 重置
                        // alert(firstDeviceId)
                    that.codeReader.decodeFromVideoDevice(firstDeviceId, 'video', (result, err) => {
                        that.tipMsg = '正在尝试识别...'
                            // let nowContent = null
                        that.textContent = null
                        if (result) {
                            alert(result);
                            that.textContent = result.text;
                            if (that.textContent) {
                                that.tipShow = false
                                that.msgBoxFunc(that.textContent)
                            }
                        }
                        if (err && !(err)) {
                            that.tipMsg = '识别失败'
                            setTimeout(() => {
                                that.tipShow = false
                                alert('识别失败')
                            }, 2000)
                            console.error(err);
                        }
                    });
                },
                // that.$createDialog 是 cube-ui滴滴 messageBox ,到这一步 二维码值已出，这里是可有可无的代码块，看各自项目ui使用情况 自行替换 messageBox
                msgBoxFunc(textContent) {
                    const that = this
                        // alert('8执行了 msgBoxFunc(),textContent:' + textContent)
                        // cube-ui messageBox
                    that.$createDialog({
                        type: 'prompt',
                        // icon: 'cubeic-alert',
                        title: '识别内容',
                        // content: that.textContent,
                        prompt: {
                            value: textContent,
                            placeholder: '请输入'
                        },
                        confirmBtn: {
                            text: '确定内容',
                            active: true,
                            disabled: false,
                            href: 'javascript:;'
                        },
                        cancelBtn: {
                            text: '继续识别',
                            active: false,
                            disabled: false,
                            href: 'javascript:;'
                        },
                        onConfirm: (e, promptValue) => {
                            // that.hide()
                            console.log('onConfirm: ()')
                            that.vin = promptValue
                        },
                        onCancel: () => {
                            console.log('onCancel: ()')
                            that.$nextTick(() => {
                                that.openScanTwo()
                            })
                        }
                    }).show()
                },
                // msgBoxFunc2() 整块代码是mint-ui  messageBox示例用，此处未使用，可直接注释；
                // msgBoxFunc2(textContent) {
                //     // mint-ui  messageBox  有重复 inputValue值问题，新调用 显示是旧的值
                //     const that = this
                //         // alert('8执行了 msgBoxFunc(),textContent:' + textContent)
                //     MessageBox.prompt('识别内容', {
                //         inputValidator: (val) => {
                //             if (val === null) {
                //                 return true; //初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
                //             }
                //         },
                //         confirmButtonText: '确定内容',
                //         cancelButtonText: '继续识别',
                //         inputValue: textContent,
                //     }).then(({
                //         value,
                //         action
                //     }) => {
                //         if (action === 'confirm') {
                //             that.vin = value
                //         }
                //         if (action === 'cancel') {
                //             that.$nextTick(() => {
                //                 that.openScanTwo()
                //             })
                //         }
                //     }).catch(err => {
                //         console.log(err);
                //     })
                // }
            }
        })
    </script>
</body>

</html>